package P056_ChooseStringJoinMethod;

import org.junit.Test;

/**
 * Desc:&emsp;&ensp;自由选择字符串拼接方法，使用+更符合阅读习惯，大多是情况下性能优化应该放在算法和数据结构上
 *
 * @author 李渊&emsp;liyuan7@yusys.com.cn
 * @version 1.0
 * @since V4.3&emsp;2022/3/24
 */
public class ChooseStringJoinMethod {
    @Test
    public void Test1() {
        long startTime = System.currentTimeMillis();
        doWithAdd();
        long takeTime1 = System.currentTimeMillis() - startTime;
        doWithConcat();
        long takeTime2 = System.currentTimeMillis() - takeTime1 - startTime;
        doWithStringBuffer();
        long takeTime3 = System.currentTimeMillis() - takeTime1 - takeTime2 - startTime;
        System.out.println("String + String: " + takeTime1 + "ms");
        System.out.println("String.Concat: " + takeTime2 + "ms");
        System.out.println("StringBuffer: " + takeTime3 + "ms");
    }

    public void doWithAdd() {
        String str = "a";
        for (int i = 0; i < 50000; i++) {
            str += "c";
            // 等价于str = new StringBuilder(Str).append("c").toString();非常耗时
        }
    }

    public void doWithConcat() {
        String str = "a";
        for (int i = 0; i < 50000; i++) {
            // concat是数组拷贝，但最后返回了一个新的String对象比较耗时
            str = str.concat("c");
        }
    }

    public void doWithStringBuffer() {
        StringBuffer sb = new StringBuffer("a");
        for (int i = 0; i < 50000; i++) {
            // 没有新建对象操作，基本都是字符串数组处理
            sb.append("c");
        }
        String str = sb.toString();
    }

}
